package android.os;

import android.util.Printer;

public class Looper {
    private static ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();
    private static Looper sMainLooper;
    MessageQueue mQueue;

    private Looper() {
        mQueue = new MessageQueue();
    }

    public static void prepareMainThread() {
        prepare();
        sMainLooper = sThreadLocal.get();
    }

    public static Looper getMainLooper() {
        // TODO:外部没有prepareMainThread()，这里为了测试通过，需要主动prepareMainThread()
        if (sMainLooper == null)
            prepareMainThread();
        return sMainLooper;
    }

    public static void prepare() {
        if (sThreadLocal.get() != null) {
            throw new IllegalStateException("each thread should not has more than one looper");
        }
        sThreadLocal.set(new Looper());
    }

    public static Looper myLooper() {
        return sThreadLocal.get();
    }

    public static void loop() {
        loop(false);
    }

    public static void loop(boolean test) {
        Looper looper = test ? getMainLooper() : myLooper();
        MessageQueue mMessageQueue = looper.mQueue;
        for (; ; ) {
            Message msg = mMessageQueue.next();
            if (msg == null) {
                return;
            }
            msg.target.dispatchMessage(msg);
            msg.recycleUnchecked();
        }
    }

    public void dump(Printer pw, String prefix) {
        pw.println(prefix + toString());
        mQueue.dump(pw, prefix + "  ", null);
    }
}